<template>
    <div style="padding: 20px 20px;">
        <div style="display: inline-flex;margin-bottom: 20px;">
            <div >
                <img style="width: 60px;height: 60px;" src="https://www.ketangpai.com/images/web2x_zuoye.png">
                <br/>
                <div style="font-size: 13px;text-align: center;margin-top: 10px;">{{ workInfo.activity }}</div>
            </div>
            <div style="margin-left: 20px;">
                <div style="margin-bottom: 30px;margin-top: 10px;">{{ workInfo.title }}</div>
                <div style="display: inline-flex;font-size: 12px;">
                    <div style="border-radius: 4px;padding: 0 5px;background-color: #ecf5ff;border:1px solid #d9ecff;color: #409EFF;">{{ workInfo.type === 1 ? '个人作业' : '小组作业' }}</div>
                    <div style="border-radius: 4px;padding: 0 5px;background-color: #ecf5ff;border:1px solid #d9ecff;color: #409EFF;">提交截止时间：{{ workInfo.endTime }}</div>
                    <div style="border-radius: 4px;padding: 0 5px;background-color: #f4f4f5;border:1px solid #e9e9eb;color: #909399;">{{ workInfo.score }}分</div>
                </div>
            </div>
        </div>
        <div class="xian"></div>
        <div>
            <div style="display: flex;align-items: center;justify-content: space-between;">
                <div style="font-size: larger;">{{ isSubmitted ? '修改提交' : '提交内容' }}</div>
                <div>
                    <el-button type="primary" @click="submitWork">{{ isSubmitted ? '确认修改' : '确认提交' }}</el-button>
                </div>
            </div>
            <br/>
            <div style="border: 1px solid #dadce0;padding: 50px 20px;border-radius: 10px;">
                <!-- 已提交状态下显示当前提交信息 -->
                <template v-if="isSubmitted">
                    <div style="margin-bottom: 20px;">
                        <div style="font-weight: bold;margin-bottom: 10px;">当前提交状态</div>
                        <div style="display: flex;align-items: center;margin-bottom: 10px;">
                            <div style="color: #67C23A;margin-right: 10px;">
                                <i class="el-icon-check"></i> 已提交
                            </div>
                            <div style="color: #909399;font-size: 13px;">
                                提交时间：{{ stuWork.submitTime }}
                            </div>
                        </div>
                    </div>
                    
                    <div style="margin-bottom: 20px;" v-if="stuWork.file">
                        <div style="font-weight: bold;margin-bottom: 10px;">当前提交文件</div>
                        <div style="background-color: #f8f9fa;padding: 10px;border-radius: 4px;display: flex;align-items: center;">
                            <i class="el-icon-document" style="margin-right: 8px;"></i>
                            <span>{{ stuWork.file.name }}</span>
                        </div>
                    </div>
                </template>
                
                <div style="margin-bottom: 10px;">{{ isSubmitted ? '修改作业附件' : '作业附件' }}</div>
                <el-upload action="" :http-request="onUpload" style="background-color: #f8f9fa;text-align: center;">
                    <p style="color: #4285f4;">点击上传{{ isSubmitted ? '修改' : '添加' }}作业文件</p>
                    <br/>
                    <p style="color: #74787c;margin-left: 8px;">支持各类文档、图片、代码、压缩包格式</p>
                </el-upload>
                <div>
                    "作业留言"
                    <span>选填</span>
                </div>
                <br/>
                <div>
                    <el-input 
                        type="textarea" 
                        style="min-height: 95.4815px; height: 95.4815px;" 
                        :placeholder="isSubmitted ? '添加修改说明...' : '作业以附件形式提交，留言仅作备注使用哦！'" 
                        v-model="stuWork.message">
                    </el-input>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { getWorkInfo } from '@/api/work';
import { getFormData } from '@/utils/getFormData';
import { get } from '@/utils/request';
import Storage from '@/utils/storage';
import { ElMessage } from 'element-plus';
import { onMounted, ref, computed } from 'vue';
import moment from "moment";
import { post } from '@/utils/httpService';
// import router from '@/router/index';

const workId = Storage.getSession("workId");
const workInfo = ref({})
const userId = Storage.getSession("user").id;
const works = ref([]);
const courseId = Storage.getSession("currentCourseMember").id;
const stuWork = ref({
    id: 0,
    status: 0,
    workId: workId,
    userId: userId,
    username: Storage.getSession("user").name,
    submitTime: null,
    message: '',
    submitCount: 0,
    content: null,
    score: null
})

// 计算属性：判断是否已提交作业
const isSubmitted = computed(() => {
    return stuWork.value && stuWork.value.status === 1;
});

// 获取作业信息
const fetchWorkInfo = async () => {
    try {
        console.log('开始获取作业信息，workId:', workId, 'type:', typeof workId)
        if (!workId) {
            throw new Error('作业ID不能为空')
        }
        const res = await getWorkInfo(workId)
        console.log('作业信息接口返回：', res)
        const date = new Date(res.data.endTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        res.data.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        workInfo.value = res.data
        console.log('作业信息：', workInfo.value)
    } catch (error) {
        console.error('获取作业信息失败：', error)
        ElMessage.error(error.message || '获取作业信息失败')
    }
};

//获取当前用户作业信息
const getUserWork = async () => {
    try {
        get(`api/work/stuwork/selectByUCid/${courseId}/${userId}`).then(res => {
        console.log("获取学生作业的响应：", res);
        if (res) {
          works.value = res.data;
           // 格式化 endTime 属性
            works.value.forEach(item => {
                if (item.endTime) {
                    const date = new Date(item.endTime);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    item.endTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                }
                if (item.submitTime) {
                    const date = new Date(item.submitTime);
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    item.submitTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                }
                console.log(item)

                if (item.workId == workId) {
                    console.log(item)
                    stuWork.value.id = item.id;
                    stuWork.value.submitTime = item.submitTime
                    stuWork.value.content = item.content
                    stuWork.value.content = item.submitCount
                    stuWork.value.message = item.message
                    stuWork.value.status=item.status
                    console.log(stuWork)
                }
            });

        }else {
          console.error("未获取到学生作业数据", res);
        }
      }).catch(error => {
        console.error("请求失败：", error);
      });
    } catch (e) {
        console.log(e);
    }
}

// 提交作业
const submitWork = () => {
    if (stuWork.value.file == null) return ElMessage.error("未上传作业");
    stuWork.value.submitTime = getCurrentTime();
    console.log(stuWork.value);
    
    if (stuWork.value.checkTime) {
        const date = new Date(stuWork.value.checkTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        stuWork.value.checkTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    stuWork.value.status = 1;
    stuWork.value.score = null;
    stuWork.value.submitCount += 1;
    const formData = getFormData(stuWork.value);

    console.log("FormData 内容：");
    formData.forEach((value, key) => {
        console.log(`${key}: ${value}`);
    });
    post('api/work/stuwork/update', formData)
        .then(res => {
            console.log(res);
            if (res) {
                if (isSubmitted.value) {
                    ElMessage.success("修改提交成功");
                    // 刷新当前页面数据
                    getUserWork();
                } else {
                    ElMessage.success("提交成功");
                }
            }
        })
        .catch(error => {
            console.error('请求出错:', error);
            // 可以在这里添加更详细的错误处理逻辑，比如显示错误提示信息
        });
};

const onUpload = (file) => {
    stuWork.value.file = file.file;
};

const getCurrentTime = () => {
    return moment().format("YYYY-MM-DD HH:mm:ss");
}

// 生命周期钩子
onMounted(() => {
    fetchWorkInfo();
    getUserWork();
    console.log(stuWork.value)
})
</script>
<style>
.xian {
    width: 100%;
    height: 1px;
    border-bottom: 1px solid #e7ebf0;
    margin: 12px 0;
}
</style>